import { OSS_FILE_URL, OSS_IMG_URL } from '@/api/ds';
import dayjs from "dayjs";
import {Solar} from 'lunar-javascript';

export function isObject(value) {
  return !isNil(value) && Object.prototype.toString.call(value) === '[object Object]';
}

export function map2query(query, question) {
  query ||= {};

  const array = [];
  for (const n of Object.keys(query)) {
    array.push(`${n}=${encodeURIComponent(query[n] || '')}`);
  }

  return (question && array.length > 0 ? '?' : '') + array.join('&');
}

export function jointPath(path, params) {
  params ||= {};

  if (Object.keys(params).length < 1) {
    return path;
  }

  if (path.indexOf('?') > -1) {
    if (!path.endsWith('&')) {
      path += '&';
    }
  } else {
    path += '?';
  }

  return path + map2query(params);
}

export function isNil(value) {
  return value == null || typeof value === 'undefined';
}

export function copy(source) {
  source ??= null;
  return isNil(source) ? null : JSON.parse(JSON.stringify(source));
}

export function exist(value, source) {
  if (typeof value === 'undefined' || isNil(source)) {
    return false;
  }

  if (Array.isArray(source)) {
    if (Array.isArray(value)) {
      for (const o of value) {
        if (source.findIndex((z) => z === o) > -1) {
          return true;
        }
      }
    } else {
      return source.findIndex((z) => z === value) > -1;
    }
  } else if (!isNil(source)) {
    return value in source;
  }

  return false;
}

export function round(value, digit) {
  value = typeof value === 'number' ? value : parseFloat(value ?? '0.0');
  digit ??= 2;

  value = parseFloat(value.toFixed(5));
  const radio = digit === 1 ? 10 : digit === 2 ? 100 : 1000;

  return Math.round(value * radio) / radio;
}

export function getAttachment(source) {
  const item = source?.find((o) => o.status === 'uploading');

  if (item) {
    throw new Error(`文件【${item.name}】正在上传中`);
  }

  return source?.filter((o) => o.status === 'done');
}

export function initFileAttachment(source, fields) {
  const result = {};
  fields ??= [];

  for (const key of fields) {
    const value = source[key];

    if (typeof value === 'string' && !!value) {
      result[key] = [{ url: OSS_FILE_URL(value), status: 'done' }];
    }
  }

  return result;
}

export function initImgAttachment(source, fields) {
  const result = {};
  fields ??= [];

  for (const key of fields) {
    const value = source[key];

    if (typeof value === 'string' && !!value) {
      result[key] = [{ url: OSS_IMG_URL(value), status: 'done' }];
    }
  }

  return result;
}

//阳历转阴历
export function solar2Lunar(value){
 return value? Solar.fromDate(dayjs(value).toDate()).getLunar()?.toString():null;
}
